const { app,BrowserWindow  }  = require('electron')
const path = require('path')
const fs = require('fs')

// 规避可能被开启的 DevTools 渲染调试叠层（FPS/paint 等）带来的绿色方块：
// 通过给开发环境设置一个干净的 userData 目录，清空历史偏好。
if (!app.isPackaged) {
  app.setPath('userData', path.join(app.getPath('temp'), 'electron-demo-dev-profile'))
}

// 打包环境：清理可能导致绿色调试叠层的 DevTools 偏好文件
function clearDevtoolsOverlaysInPackaged() {
  if (!app.isPackaged) return
  const userData = app.getPath('userData')
  const targets = [
    path.join(userData, 'Preferences'),
    path.join(userData, 'DevTools Extensions'),
  ]
  for (const p of targets) {
    try { fs.rmSync(p, { force: true }) } catch (_e) { /* ignore */ }
  }
}

// 简单的本地闪屏（通过 data URL 内联），避免启动白屏
const createSplash = () => {
  const splash = new BrowserWindow({
    width: 420,
    height: 280,
    useContentSize: true,
    frame: false,
    alwaysOnTop: true,
    resizable: false,
    transparent: false,
    show: false,
    backgroundColor: '#111111',
    webPreferences: { backgroundThrottling: false }
  })
  const html = `
  <html>
    <head>
      <meta charset='utf-8' />
      <title>Loading</title>
      <style>
        html,body{height:100%;margin:0;background:#111;color:#fff;font-family:system-ui,Segoe UI,Roboto,Helvetica,Arial}
        .wrap{height:100%;display:flex;align-items:center;justify-content:center;flex-direction:column}
        .spinner{width:56px;height:56px;border:6px solid rgba(255,255,255,.2);border-top-color:#4ea1ff;border-radius:50%;animation:spin 1s linear infinite}
        @keyframes spin{to{transform:rotate(360deg)}}
        .tip{margin-top:12px;opacity:.8}
      </style>
    </head>
    <body>
      <div class='wrap'>
        <div class='spinner'></div>
        <div class='tip'>正在加载，请稍候…</div>
      </div>
    </body>
  </html>`
  splash.loadURL('data:text/html;charset=utf-8,' + encodeURIComponent(html))
  splash.once('ready-to-show', () => splash.show())
  return splash
}

const createWindow = () => {
  const splash = createSplash()

  const win = new BrowserWindow({
    width: 800,
    height: 600,
    fullscreen: true,
    autoHideMenuBar: true,
    backgroundColor: '#ffffff',
    show: false,
  })

  // 加载线上地址（主窗口先隐藏，避免白屏）
  win.loadURL('https://pinia.vuejs.org/zh/')

  // 监听 ESC 退出应用
  win.webContents.on('before-input-event', (_event, input) => {
    if (input.type === 'keyDown' && input.key && input.key.toLowerCase() === 'escape') {
      app.quit()
    }
  })

  // 页面完成首帧渲染后再显示主窗口，并关闭闪屏
  win.once('ready-to-show', () => {
    win.show()
    if (!splash.isDestroyed()) splash.close()
  })

  // 网络失败时给出简单提示，避免长期白屏
  win.webContents.on('did-fail-load', () => {
    if (!splash.isDestroyed()) splash.close()
    win.show()
    win.loadURL('data:text/plain;charset=utf-8,加载失败，请检查网络连接。')
  })
}
app.whenReady().then(() => {
  clearDevtoolsOverlaysInPackaged()
  createWindow()
   app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})